﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using He.Common;
using He.Model;

namespace He.BLL
{
    public class config
    {
        private static object lockHelper = new object();

        #region He配置读写
        //private readonly string FilePathCms = "~/config/cms.config";
        //public void SaveCmsConfig(ConfigCms model)
        //{
        //    this.SaveConfig<ConfigCms>(model, this.FilePathCms);
        //}
        //public ConfigCms LoadCmsConfig()
        //{
        //    return this.LoadConfig<ConfigCms>(this.FilePathCms);
        //}
        #endregion


        /// <summary>
        /// 保存配置文件
        /// </summary>
        /// <param name="model"></param>
        /// <param name="filePath">服务器相对路径</param>
        public void SaveConfig<T>(T model, string filePath)
        {
            lock (lockHelper)
            {
                XmlHelper.Save(model, PathHelper.MapPath(filePath));
            }
        }

        /// <summary>
        /// 读取配置文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public T LoadConfig<T>(string filePath) where T : class, new()
        {
            string cacheName = "Cache_Config" + filePath;
            //从缓存中根据键读取，并使用as转换
            T model = CacheHelper.Get(cacheName) as T;
            if (model == null)
            {
                string absoluteFilePath = PathHelper.MapPath(filePath);
                model = XmlHelper.Load(typeof(T), absoluteFilePath) as T;
                CacheHelper.Add(cacheName, model, absoluteFilePath);
            }
            return model;
        }
    }
}
